package com.sirui.spider.kuai.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sirui.mongo.file.MongoGridFSService;
import com.sirui.spider.kuai.entity.CommonConstants;
import com.sirui.spider.kuai.entity.Kuai;
import com.sirui.spider.kuai.repository.KuaiRepository;
import com.sirui.spider.kuai.service.KuaiService;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * (Kuai)表服务实现类
 *
 * @author linson
 * @since 2023/07/12
 */
@Slf4j
@Service("kuaiService")
public class KuaiServiceImpl implements KuaiService {

    @Autowired
    private KuaiRepository kuaiRepository;

    @Autowired
    private MongoGridFSService mongoGridFSService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Transactional(readOnly = false, value = CommonConstants.Config_transactionManager_Name)
    public Kuai createKuai(Kuai kuai) {
        kuaiRepository.save(kuai);
        return kuai;
    }

    @Override
    public void deleteKuai(Integer id) {
        kuaiRepository.deleteById(id);
    }

    @Override
    public List<Kuai> listKuais() {
        return kuaiRepository.findAll();
    }

    @Override
    public Kuai getKuai(Integer id) {
        Optional<Kuai> optional = kuaiRepository.findById(id);
        if (!optional.isPresent()) {
            throw new RuntimeException();
        }
        return optional.get();
    }

    @Override
    public Kuai updateKuai(Integer id, Kuai kuai) {
        return kuaiRepository.save(kuai);
    }

    @Override
    public void downPics2Mongo() {
        Specification<Kuai> specification = new Specification<Kuai>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                //Predicate conjunction = criteriaBuilder.conjunction();
                //conjunction.getExpressions().add(criteriaBuilder.equal(root.get("savePicStatus"), false));
                //conjunction.getExpressions().add(criteriaBuilder.isNull(root.get("savePicStatus")));
                //return conjunction;

                Predicate predicate = query.where(
                        criteriaBuilder.or(
                                criteriaBuilder.isNull(root.get("savePicStatus")),
                                criteriaBuilder.equal(root.get("savePicStatus"), false)
                        )
                ).getRestriction();
                return predicate;

                //List<Predicate> condition = new ArrayList<>();
                //condition.add(criteriaBuilder.equal(root.get("savePicStatus"), false));
                //condition.add(criteriaBuilder.isNull(root.get("savePicStatus")));
                //Predicate[] predicates = new Predicate[condition.size()];
                //query.where(criteriaBuilder.or(condition.toArray(predicates)));
                //return query.getRestriction();
            }
        };

        List<Kuai> list = kuaiRepository.findAll(specification);
        log.info(String.format("A@@A [%s]", list.size()));
        for (int i = 0; i < list.size(); i++) {
            if (i == 3) {
                break;
            }
            Kuai kuai = list.get(i);
            String id = kuai.getId();
            String content = kuai.getContent();
            JSONObject jsonObject = JSONUtil.parseObj(content);
            String title = (String) jsonObject.get("title");
            log.info(String.format("A@@A [%s]", title));
            List<String> imgHrefList = (List<String>) jsonObject.get("imgHrefList");
            for (int index = 0; index < imgHrefList.size(); index++) {
                String href = imgHrefList.get(index);
                href = "http:" + href;
                log.info(String.format("A@@A [%s]", href));
                String suffix = href.substring(href.lastIndexOf(".") - 1);
                File tempFile = null;
                try {
                    tempFile = FileUtil.createTempFile("img_", suffix, true);
                    log.info(String.format("A@@A [%s]", tempFile));
                    HttpUtil.downloadFile(href, tempFile);
                    Document document = new Document("objId", id);
                    document.put("index", index);
                    mongoGridFSService.saveToGridFS("images", tempFile, document);
                    tempFile.delete();
                } catch (Exception e) {
                    log.info(String.format("A@@A [%s]", e.getMessage()));
                } finally {
                    if (tempFile != null) {
                        tempFile.delete();
                    }
                }
            }
            kuai.setSavePicStatus(true);
            kuai.setUpdateDate(new Date());
            kuaiRepository.save(kuai);
        }
    }

    @Override
    @Transactional(readOnly = false, value = CommonConstants.Config_transactionManager_Name)
    public void deleteKuaiByIds(Integer[] ids) {
        kuaiRepository.deleteByIdIn(Arrays.asList(ids));
    }


}

